package com.shenmazong.serverwebpoem.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.code.kaptcha.Constants;
import com.shenmazong.serverwebpoem.pojo.*;
import com.shenmazong.serverwebpoem.service.*;
import com.shenmazong.serverwebpoem.util.ParamUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 田不平
 * @project server-web-poem
 * @date 2020/3/31 12:28 PM
 * http://www.shenmazong.com
 */

@Slf4j
@Controller
@RequestMapping(value = "/admin")
public class AdminController {

    @Autowired
    TbAdminService tbAdminService;

    @Autowired
    TbPoetryInfoService tbPoetryInfoService;

    @Autowired
    TbNoteService tbNoteService;

    @Autowired
    TbTranslateService tbTranslateService;

    @Autowired
    TbAppreciationService tbAppreciationService;

    @Autowired
    TbStoryService tbStoryService;

    @Autowired
    ElasticSearchService elasticService;

    /**
     * TODO 检查是否登录
     * @param request
     * @return
     */
    private Boolean isLogin(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String adminName = (String)session.getAttribute("adminName");
        if(adminName == null || adminName.equals("")) {
            return false;
        }

        return true;
    }

    /**
     * TODO 管理后台首页
     * @param request
     * @return
     */
    @RequestMapping(value = {"/", "/index"})
    public String index(HttpServletRequest request) {
        //-- 检查是否登录
        if(!isLogin(request)) {
            return "admin/login";
        }

        //-- 已登录
        return "admin/index";
    }

    /**
     * TODO 管理后台登录
     * @return
     */
    @RequestMapping(value = "login")
    public String login(HttpServletRequest request, Model model) {

        //-- 已经登录
        if(isLogin(request)) {
            return "admin/index";
        }

        //-- 校验验证码
        String verifyCode = ParamUtils.getParameter(request, "verifycode", "");
        if(verifyCode == null || verifyCode.length() == 0) {
            log.info("login, 验证码错误...");
            model.addAttribute("msg", "验证码错误");
            return "admin/login";
        }
        String realCode = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if(!realCode.equals(verifyCode)) {
            log.info("login, 验证码错误...");
            model.addAttribute("msg", "验证码错误");
            return "admin/login";
        }

        //-- 提交登录
        String userName = ParamUtils.getParameter(request, "username", "");
        String userPass = ParamUtils.getParameter(request, "password", "");

        log.info("admin={},pass={}", userName, userPass);

        if(userName.equals("") || userPass.equals("")) {
            model.addAttribute("msg", "用户名和密码错误！");
            return "admin/login";
        }

        //-- 验证用户名和密码
        TbAdmin admin = tbAdminService.getByName(userName);
        if(admin == null) {
            model.addAttribute("msg", "用户不存在！");
            return "admin/login";
        }
        if(!admin.getUserpass().equals(userPass)) {
            model.addAttribute("msg", "密码错误！");
            return "admin/login";
        }

        //-- 存储管理用户
        HttpSession session = request.getSession();
        session.setAttribute("adminName", userName);

        return "redirect:/admin/index";
    }

    @GetMapping(value = "/note/{id}")
    public String note(HttpServletRequest request, Model model,
                       @PathVariable(name = "id") Integer id) {
        //-- 检查是否登录
        if(!isLogin(request)) {
            return "admin/login";
        }

        //-- 获取列表
        //Integer pageNo = ParamUtils.getIntParameter(request, "id", 1);
        Integer pageNo = id;
        IPage<TbNote> iPage = tbNoteService.getNoteByPage(pageNo, 5);
        List<TbNote> poetries = iPage.getRecords();

        model.addAttribute("poetries", poetries);

        //-- 分页处理
        model.addAttribute("pageCurrent", pageNo);
        model.addAttribute("pageSize", 5);
        model.addAttribute("pageCount", iPage.getPages());
        model.addAttribute("count", iPage.getTotal());

        if(pageNo < 5) {
            List<Integer> pages = new ArrayList<>();
            for(Integer idx=1; idx<8; idx++) {
                if(idx>iPage.getPages())
                    break;
                pages.add(idx);
            }
            model.addAttribute("pages", pages);
        }
        else {
            List<Integer> pages = new ArrayList<>();
            for(Integer idx=pageNo-3; idx<pageNo+4; idx++) {
                if(idx>iPage.getPages())
                    break;
                pages.add(idx);
            }
            model.addAttribute("pages", pages);
        }

        return "admin/note";
    }


    @PostMapping(value = "/doNoteVerify")
    @ResponseBody
    public Object doNoteVerify(HttpServletRequest request) {

        Map<String,Object> resultMap = new HashMap<>();

        //-- 检查是否登录
        if(!isLogin(request)) {
            resultMap.put("result", -1);
            resultMap.put("msg", "未登录");
            return resultMap;
        }

        //-- 获取审核信息
        Integer id = ParamUtils.getIntParameter(request, "id", 0);
        if(id <= 0) {
            resultMap.put("result", -1);
            resultMap.put("msg", "参数违法");
            return resultMap;
        }
        TbNote note = tbNoteService.getById(id);
        if(note == null) {
            resultMap.put("result", -1);
            resultMap.put("msg", "数据不存在");
            return resultMap;
        }

        //-- 修改记录
        if(note.getVerify()>0)
            note.setVerify(0);
        else
            note.setVerify(1);
        tbNoteService.set(note);

        resultMap.put("result", 0);
        resultMap.put("data", note);
        return resultMap;
    }

    @PostMapping(value = "/doNoteDelete")
    @ResponseBody
    public Object doNoteDelete(HttpServletRequest request) {
        Map<String,Object> resultMap = new HashMap<>();

        //-- 检查是否登录
        if(!isLogin(request)) {
            resultMap.put("result", -1);
            resultMap.put("msg", "未登录");
            return resultMap;
        }

        //-- 获取审核信息
        Integer id = ParamUtils.getIntParameter(request, "id", 0);
        if(id <= 0) {
            resultMap.put("result", -1);
            resultMap.put("msg", "参数违法");
            return resultMap;
        }
        TbNote note = tbNoteService.getById(id);
        if(note == null) {
            resultMap.put("result", -1);
            resultMap.put("msg", "数据不存在");
            return resultMap;
        }

        //-- 删除记录
        tbNoteService.del(note.getId());

        resultMap.put("result", 0);
        resultMap.put("data", note);
        return resultMap;
    }

    @GetMapping(value = "/translate/{id}")
    public String translate(HttpServletRequest request, Model model,
                       @PathVariable(name = "id") Integer id) {
        //-- 检查是否登录
        if(!isLogin(request)) {
            return "admin/login";
        }

        //-- 获取列表
        //Integer pageNo = ParamUtils.getIntParameter(request, "id", 1);
        Integer pageNo = id;
        IPage<TbTranslate> iPage = tbTranslateService.getNoteByPage(pageNo, 5);
        List<TbTranslate> poetries = iPage.getRecords();

        model.addAttribute("poetries", poetries);

        //-- 分页处理
        model.addAttribute("pageCurrent", pageNo);
        model.addAttribute("pageSize", 5);
        model.addAttribute("pageCount", iPage.getPages());
        model.addAttribute("count", iPage.getTotal());

        if(pageNo < 5) {
            List<Integer> pages = new ArrayList<>();
            for(Integer idx=1; idx<8; idx++) {
                if(idx>iPage.getPages())
                    break;
                pages.add(idx);
            }
            model.addAttribute("pages", pages);
        }
        else {
            List<Integer> pages = new ArrayList<>();
            for(Integer idx=pageNo-3; idx<pageNo+4; idx++) {
                if(idx>iPage.getPages())
                    break;
                pages.add(idx);
            }
            model.addAttribute("pages", pages);
        }

        return "admin/translate";
    }


    @PostMapping(value = "/doTranslateVerify")
    @ResponseBody
    public Object doTranslateVerify(HttpServletRequest request) {

        Map<String,Object> resultMap = new HashMap<>();

        //-- 检查是否登录
        if(!isLogin(request)) {
            resultMap.put("result", -1);
            resultMap.put("msg", "未登录");
            return resultMap;
        }

        //-- 获取审核信息
        Integer id = ParamUtils.getIntParameter(request, "id", 0);
        if(id <= 0) {
            resultMap.put("result", -1);
            resultMap.put("msg", "参数违法");
            return resultMap;
        }
        TbTranslate translate = tbTranslateService.getById(id);
        if(translate == null) {
            resultMap.put("result", -1);
            resultMap.put("msg", "数据不存在");
            return resultMap;
        }

        //-- 修改记录
        if(translate.getVerify()>0)
            translate.setVerify(0);
        else
            translate.setVerify(1);
        tbTranslateService.set(translate);

        resultMap.put("result", 0);
        resultMap.put("data", translate);
        return resultMap;
    }

    @PostMapping(value = "/doTranslateDelete")
    @ResponseBody
    public Object doTranslateDelete(HttpServletRequest request) {
        Map<String,Object> resultMap = new HashMap<>();

        //-- 检查是否登录
        if(!isLogin(request)) {
            resultMap.put("result", -1);
            resultMap.put("msg", "未登录");
            return resultMap;
        }

        //-- 获取审核信息
        Integer id = ParamUtils.getIntParameter(request, "id", 0);
        if(id <= 0) {
            resultMap.put("result", -1);
            resultMap.put("msg", "参数违法");
            return resultMap;
        }
        TbTranslate translate = tbTranslateService.getById(id);
        if(translate == null) {
            resultMap.put("result", -1);
            resultMap.put("msg", "数据不存在");
            return resultMap;
        }

        //-- 删除记录
        tbTranslateService.del(translate.getId());

        resultMap.put("result", 0);
        resultMap.put("data", translate);
        return resultMap;
    }

    @GetMapping(value = "/appreciation/{id}")
    public String appreciation(HttpServletRequest request, Model model,
                            @PathVariable(name = "id") Integer id) {
        //-- 检查是否登录
        if(!isLogin(request)) {
            return "admin/login";
        }

        //-- 获取列表
        //Integer pageNo = ParamUtils.getIntParameter(request, "id", 1);
        Integer pageNo = id;
        IPage<TbAppreciation> iPage = tbAppreciationService.getNoteByPage(pageNo, 5);
        List<TbAppreciation> poetries = iPage.getRecords();

        model.addAttribute("poetries", poetries);

        //-- 分页处理
        model.addAttribute("pageCurrent", pageNo);
        model.addAttribute("pageSize", 5);
        model.addAttribute("pageCount", iPage.getPages());
        model.addAttribute("count", iPage.getTotal());

        if(pageNo < 5) {
            List<Integer> pages = new ArrayList<>();
            for(Integer idx=1; idx<8; idx++) {
                if(idx>iPage.getPages())
                    break;
                pages.add(idx);
            }
            model.addAttribute("pages", pages);
        }
        else {
            List<Integer> pages = new ArrayList<>();
            for(Integer idx=pageNo-3; idx<pageNo+4; idx++) {
                if(idx>iPage.getPages())
                    break;
                pages.add(idx);
            }
            model.addAttribute("pages", pages);
        }

        return "admin/appreciation";
    }


    @PostMapping(value = "/doAppreciationVerify")
    @ResponseBody
    public Object doAppreciationVerify(HttpServletRequest request) {

        Map<String,Object> resultMap = new HashMap<>();

        //-- 检查是否登录
        if(!isLogin(request)) {
            resultMap.put("result", -1);
            resultMap.put("msg", "未登录");
            return resultMap;
        }

        //-- 获取审核信息
        Integer id = ParamUtils.getIntParameter(request, "id", 0);
        if(id <= 0) {
            resultMap.put("result", -1);
            resultMap.put("msg", "参数违法");
            return resultMap;
        }
        TbAppreciation appreciation = tbAppreciationService.getById(id);
        if(appreciation == null) {
            resultMap.put("result", -1);
            resultMap.put("msg", "数据不存在");
            return resultMap;
        }

        //-- 修改记录
        if(appreciation.getVerify()>0)
            appreciation.setVerify(0);
        else
            appreciation.setVerify(1);
        tbAppreciationService.set(appreciation);

        resultMap.put("result", 0);
        resultMap.put("data", appreciation);
        return resultMap;
    }

    @PostMapping(value = "/doAppreciationDelete")
    @ResponseBody
    public Object doAppreciationDelete(HttpServletRequest request) {
        Map<String,Object> resultMap = new HashMap<>();

        //-- 检查是否登录
        if(!isLogin(request)) {
            resultMap.put("result", -1);
            resultMap.put("msg", "未登录");
            return resultMap;
        }

        //-- 获取审核信息
        Integer id = ParamUtils.getIntParameter(request, "id", 0);
        if(id <= 0) {
            resultMap.put("result", -1);
            resultMap.put("msg", "参数违法");
            return resultMap;
        }
        TbAppreciation appreciation = tbAppreciationService.getById(id);
        if(appreciation == null) {
            resultMap.put("result", -1);
            resultMap.put("msg", "数据不存在");
            return resultMap;
        }

        //-- 删除记录
        tbAppreciationService.del(appreciation.getId());

        resultMap.put("result", 0);
        resultMap.put("data", appreciation);
        return resultMap;
    }

    @GetMapping(value = "/story/{id}")
    public String story(HttpServletRequest request, Model model,
                               @PathVariable(name = "id") Integer id) {
        //-- 检查是否登录
        if(!isLogin(request)) {
            return "admin/login";
        }

        //-- 获取列表
        //Integer pageNo = ParamUtils.getIntParameter(request, "id", 1);
        Integer pageNo = id;
        IPage<TbStory> iPage = tbStoryService.getNoteByPage(pageNo, 5);
        List<TbStory> poetries = iPage.getRecords();

        model.addAttribute("poetries", poetries);

        //-- 分页处理
        model.addAttribute("pageCurrent", pageNo);
        model.addAttribute("pageSize", 5);
        model.addAttribute("pageCount", iPage.getPages());
        model.addAttribute("count", iPage.getTotal());

        if(pageNo < 5) {
            List<Integer> pages = new ArrayList<>();
            for(Integer idx=1; idx<8; idx++) {
                if(idx>iPage.getPages())
                    break;
                pages.add(idx);
            }
            model.addAttribute("pages", pages);
        }
        else {
            List<Integer> pages = new ArrayList<>();
            for(Integer idx=pageNo-3; idx<pageNo+4; idx++) {
                if(idx>iPage.getPages())
                    break;
                pages.add(idx);
            }
            model.addAttribute("pages", pages);
        }

        return "admin/story";
    }


    @PostMapping(value = "/doStoryVerify")
    @ResponseBody
    public Object doStoryVerify(HttpServletRequest request) {

        Map<String,Object> resultMap = new HashMap<>();

        //-- 检查是否登录
        if(!isLogin(request)) {
            resultMap.put("result", -1);
            resultMap.put("msg", "未登录");
            return resultMap;
        }

        //-- 获取审核信息
        Integer id = ParamUtils.getIntParameter(request, "id", 0);
        if(id <= 0) {
            resultMap.put("result", -1);
            resultMap.put("msg", "参数违法");
            return resultMap;
        }
        TbStory story = tbStoryService.getById(id);
        if(story == null) {
            resultMap.put("result", -1);
            resultMap.put("msg", "数据不存在");
            return resultMap;
        }

        //-- 修改记录
        if(story.getVerify()>0)
            story.setVerify(0);
        else
            story.setVerify(1);
        tbStoryService.set(story);

        resultMap.put("result", 0);
        resultMap.put("data", story);
        return resultMap;
    }

    @PostMapping(value = "/doStoryDelete")
    @ResponseBody
    public Object doStoryDelete(HttpServletRequest request) {
        Map<String,Object> resultMap = new HashMap<>();

        //-- 检查是否登录
        if(!isLogin(request)) {
            resultMap.put("result", -1);
            resultMap.put("msg", "未登录");
            return resultMap;
        }

        //-- 获取审核信息
        Integer id = ParamUtils.getIntParameter(request, "id", 0);
        if(id <= 0) {
            resultMap.put("result", -1);
            resultMap.put("msg", "参数违法");
            return resultMap;
        }
        TbStory story = tbStoryService.getById(id);
        if(story == null) {
            resultMap.put("result", -1);
            resultMap.put("msg", "数据不存在");
            return resultMap;
        }

        //-- 删除记录
        tbStoryService.del(story.getId());

        resultMap.put("result", 0);
        resultMap.put("data", story);
        return resultMap;
    }

    /**
     * TODO 获取用户每日信息统计
     * @return
     */
    @PostMapping(value = "/getUserEveryDay")
    @ResponseBody
    public Object getUserEveryDay(HttpServletRequest request) {
        Map<String,Object> resultMap = new HashMap<>();

        //-- 检查是否登录
        if(!isLogin(request)) {
            resultMap.put("result", -1);
            resultMap.put("msg", "未登录");
            return resultMap;
        }

        //-- 数组数据
        List<String> names = new ArrayList<>();
        List<Integer> logins = new ArrayList<>();
        List<Integer> signups = new ArrayList<>();

        //-- 测试数据
        names.add("20020201");
        names.add("20020202");
        names.add("20020203");
        names.add("20020204");

        logins.add(80);
        logins.add(100);
        logins.add(90);
        logins.add(120);

        signups.add(50);
        signups.add(60);
        signups.add(40);
        signups.add(70);

        resultMap.put("names", names);
        resultMap.put("logins", logins);
        resultMap.put("signups", signups);
        resultMap.put("result", 0);

        return resultMap;
    }

    /**
     * TODO 后台难度系数修改
     * @return
     */
    @RequestMapping(value = "/difficult")
    public String difficult(HttpServletRequest request, Model model) {

        log.debug("debug");
        // error > warn > debug > info

        String keyWord = ParamUtils.getParameter(request, "keyWord", "");
        Pageable pageable = PageRequest.of(0,5);
        Page<TbPoetry> pageData = elasticService.findByWord(keyWord, pageable);

        List<TbPoetry> poetries = pageData.getContent();

        for(Integer idx=0; idx<poetries.size(); idx++) {
            TbPoetryInfo info = tbPoetryInfoService.getByPoetryId(poetries.get(idx).getId());
            if(info == null) {
                poetries.get(idx).setDifficult(0);
            }
            else {
                poetries.get(idx).setDifficult(info.getDifficult());
            }
        }

        model.addAttribute("poetries", poetries);

        return "admin/difficult";
    }

    /**
     * TODO 设置诗词的难度
     * @param request
     * @return
     */
    @RequestMapping(value = "/setDifficult", method = RequestMethod.POST)
    @ResponseBody
    public Object setDifficult(HttpServletRequest request) {
        Map<String,Object> resultMap = new HashMap<>();

        Integer poetryId = ParamUtils.getIntParameter(request, "id", 0);
        Integer difficult = ParamUtils.getIntParameter(request, "difficult", 0);
        if(poetryId <= 0 || difficult <= 0) {
            resultMap.put("result", -1);
            resultMap.put("msg", "参数违法");
            return resultMap;
        }

        TbPoetryInfo info = tbPoetryInfoService.getByPoetryId(poetryId);
        if(info == null) {
            info = new TbPoetryInfo();
            info.setPoetryid(poetryId);
            info.setDifficult(difficult);

            tbPoetryInfoService.add(info);
        }
        else {
            info.setDifficult(difficult);
            tbPoetryInfoService.set(info);
        }

        resultMap.put("result", 0);
        resultMap.put("info", info);

        return resultMap;
    }
}
